package sk.fiit.icp.data;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public class UsersDaoImpl implements UsersDao {

	private HibernateTemplate hibernateTemplate;

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		hibernateTemplate = new HibernateTemplate(sessionFactory);
	}
	
	@Transactional(readOnly = false)
	public void persist(Users user) {
		hibernateTemplate.persist(user);
	}

	@Transactional
	public Users findById(int id) {
		return (Users) hibernateTemplate.find("from Users AS u WHERE u.id = ?", id).get(0);
	}

	@Transactional
	public Users findByEmail(String email) {
		return (Users) hibernateTemplate.find("from Users AS u WHERE u.email = ?", email).get(0);
	}

	@Transactional(readOnly = false)
	public void update(Users e) {
		hibernateTemplate.merge(e);
	}

	@Transactional
	public Users findByEmailAndPassword(String username, String password) {
		return (Users) hibernateTemplate.find("from Users AS u WHERE u.email = ? AND u.password = ?", username,
				password).get(0);

	}

}
